package com.whxd.framework.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring容器，辅助在运行时获取Spring的bean
 * 
 * @author 张世鹏
 * @since 2013-4-19
 */
public class SpringContext implements ApplicationContextAware{

	public static ApplicationContext applicationContext;

	/**
	 * 根据bean的name获取bean实例
	 * 
	 * @author 张世鹏
	 * @since 2013-4-19
	 * @param name
	 *            bean的name
	 * @return bean实例
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException{
		if (name == null) return null;
		return applicationContext.getBean(name);
	}

	/**
	 * 根据bean的class获取bean实例
	 * 
	 * @author 张世鹏
	 * @since 2013-4-19
	 * @param cls
	 *            Bean的class
	 * @return 
	 * @return bean实例
	 * @throws BeansException
	 */
	public static <T> T getBean(Class<T> cls) throws BeansException{
		if (cls == null) return null;
		return applicationContext.getBean(cls);
	}

	public void setApplicationContext(ApplicationContext contex)
			throws BeansException{
		applicationContext = contex;
	}
}
